<template>
  <div class="problem-upload">
    <SideNav />
    <div class="main-content">
      <div class="page-header">
        <h1>上传题目</h1>
        <div class="header-actions">
          <button class="submit-btn" @click="submitProblem" :disabled="isSubmitting">
            <i class="fas fa-cloud-upload-alt"></i>
            {{ isSubmitting ? '提交中...' : '提交题目' }}
          </button>
        </div>
      </div>

      <!-- 基本信息部分 -->
      <div class="section basic-info">
        <h2>基本信息</h2>
        <div class="form-group">
          <label>题目标题</label>
          <input 
            type="text" 
            v-model="problemData.title"
            placeholder="请输入题目标题"
            class="form-input"
          >
        </div>
        
        <div class="form-group">
          <label>难度等级</label>
          <select v-model="problemData.difficulty" class="form-select">
            <option value="">请选择难度</option>
            <option value="EASY">简单</option>
            <option value="MEDIUM">中等</option>
            <option value="HARD">困难</option>
          </select>
        </div>

        <div class="form-group">
          <label>题库类型</label>
          <div class="library-type-selector">
            <button 
              :class="['type-btn', { active: problemData.type === 'public' }]"
              @click="setProblemType('public')"
            >
              <i class="fas fa-globe"></i>
              公共题库
            </button>
            <button 
              :class="['type-btn', { active: problemData.type === 'group' }]"
              @click="setProblemType('group')"
            >
              <i class="fas fa-users"></i>
              小组题库
            </button>
          </div>
        </div>
      </div>

      <!-- 题目描述部分 -->
      <div class="section description">
        <h2>题目描述</h2>
        <div class="editor-container">
          <RichTextEditor 
            v-if="!isDestroying"
            v-model="problemData.description"
            class="problem-editor" 
            @upload-image="handleImageUpload"
            @delete-image="handleImageDelete"
            :preserve-images="isSubmitSuccess"
          />
        </div>
      </div>

      <!-- 执行限制部分 -->
      <div class="section limits">
        <div class="section-header">
          <h2>执行限制</h2>
          <div class="limits-toggle">
            <label class="switch">
              <input type="checkbox" v-model="problemData.hasLimits">
              <span class="slider round"></span>
            </label>
            <span class="toggle-label">启用自定义限制</span>
          </div>
        </div>

        <div v-if="problemData.hasLimits" class="limits-content">
          <div class="limit-item">
            <label>最大执行时间</label>
            <div class="limit-input-group">
              <input 
                type="number" 
                v-model.number="timeLimit"
                :min="executionLimits.timeUnit === 's' ? 0.1 : 100"
                :max="executionLimits.timeUnit === 's' ? 30 : 30000"
                :step="executionLimits.timeUnit === 's' ? 0.1 : 100"
                class="limit-input"
              >
              <select 
                v-model="executionLimits.timeUnit"
                class="unit-select"
                @change="handleTimeUnitChange"
              >
                <option value="s">秒</option>
                <option value="ms">毫秒</option>
              </select>
            </div>
          </div>
          
          <div class="limit-item">
            <label>最大内存使用</label>
            <div class="limit-input-container">
              <div class="limit-input-group">
                <input 
                  type="number" 
                  v-model.number="memoryLimit"
                  :class="['limit-input', {'invalid': !memoryInputValid}]"
                  @input="validateMemoryLimit"
                >
                <select 
                  v-model="executionLimits.memoryUnit"
                  class="unit-select"
                  @change="handleMemoryUnitChange"
                >
                  <option value="MB">MB</option>
                  <option value="KB">KB</option>
                </select>
              </div>
              <div v-if="!memoryInputValid" class="input-error">
                {{ memoryInputStatus.message }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 测试用例部分 -->
      <div class="section test-cases">
        <h2>测试用例</h2>
        <div class="test-case-tips alert">
          <i class="fas fa-info-circle"></i>
          <div>
            <h3>测试用例格式说明</h3>
            <ul>
              <li><strong>使用空格分隔</strong>输入的多个数值，如 <code>1 2 3 4 5</code>，<strong>不要使用逗号</strong></li>
              <li>多行数据请每行输入一组数据，系统会自动处理测试用例数量</li>
              <li>确保输入和预期输出格式一致，避免多余的空格、换行等</li>
            </ul>
          </div>
        </div>

        <div class="test-cases-container">
          <!-- 示例测试用例 -->
          <div class="test-case-group">
            <h3>示例测试用例</h3>
            <span class="help-text">这些测试用例会展示给用户，指导他们理解题目</span>
            <div class="test-case-list">
              <div 
                v-for="(testCase, index) in exampleTestCases" 
                :key="'example-' + index"
                class="test-case-item"
              >
                <div class="test-case-header">
                  <h4>示例 #{{index + 1}}</h4>
                  <button 
                    v-if="exampleTestCases.length > 1"
                    class="delete-btn"
                    @click="removeTestCase('example', index)"
                  >
                    <i class="fas fa-times"></i>
                  </button>
                </div>
                <div class="test-case-content">
                  <div class="input-group">
                    <label>输入</label>
                    <textarea 
                      v-model="testCase.input"
                      class="case-textarea"
                      placeholder="请输入测试数据..."
                    ></textarea>
                  </div>
                  <div class="input-group">
                    <label>预期输出</label>
                    <textarea 
                      v-model="testCase.expectedOutput"
                      class="case-textarea"
                      placeholder="请输入预期输出..."
                    ></textarea>
                  </div>
                </div>
              </div>
              <button 
                class="add-case-btn"
                @click="addTestCase('example')"
              >
                <i class="fas fa-plus"></i>
                添加示例测试用例
              </button>
            </div>
          </div>

          <!-- 评测测试用例 -->
          <div class="test-case-group">
            <h3>评测测试用例</h3>
            <span class="help-text">这些测试用例用于判断用户代码是否正确，不会展示给用户</span>
            <div class="test-case-tips alert alert-evaluation">
              <i class="fas fa-exclamation-triangle"></i>
              <div>
                <p><strong>评测用例格式与示例相同</strong>，系统会自动处理测试用例数量信息。</p>
                <p>请确保您的测试输入和预期输出格式统一，这将影响用户代码的评判准确性。</p>
              </div>
            </div>
            <div class="test-case-list">
              <div 
                v-for="(testCase, index) in evaluationTestCases" 
                :key="'eval-' + index"
                class="test-case-item"
              >
                <div class="test-case-header">
                  <h4>测试用例 #{{index + 1}}</h4>
                  <button 
                    v-if="evaluationTestCases.length > 1"
                    class="delete-btn"
                    @click="removeTestCase('evaluation', index)"
                  >
                    <i class="fas fa-times"></i>
                  </button>
                </div>
                <div class="test-case-content">
                  <div class="input-group">
                    <label>输入</label>
                    <textarea 
                      v-model="testCase.input"
                      class="case-textarea"
                      placeholder="请输入测试数据..."
                    ></textarea>
                  </div>
                  <div class="input-group">
                    <label>预期输出</label>
                    <textarea 
                      v-model="testCase.expectedOutput"
                      class="case-textarea"
                      placeholder="请输入预期输出..."
                    ></textarea>
                  </div>
                </div>
              </div>
              <button 
                class="add-case-btn"
                @click="addTestCase('evaluation')"
              >
                <i class="fas fa-plus"></i>
                添加评测测试用例
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交确认对话框 -->
    <MessagePopup
      :visible="showConfirmDialog"
      type="warning"
      title="确认提交"
      message="确定要提交此题目吗？提交后将进入审核流程。"
      :showConfirm="true"
      :showCancel="true"
      confirmText="确认提交"
      cancelText="取消"
      :duration="0"
      @update:visible="showConfirmDialog = $event"
      @confirm="handleConfirmSubmit"
      @cancel="showConfirmDialog = false"
    />

    <!-- 结果提示 -->
    <MessagePopup
      :visible="showMessage"
      :type="messageType"
      :title="messageTitle"
      :message="messageText"
      :duration="2000"
      @update:visible="showMessage = $event"
    />

    <!-- 选择小组模态框 -->
    <div class="modal" v-if="showGroupSelector">
      <div class="modal-overlay" @click="handleCancelGroupSelect"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h3>选择小组</h3>
          <button class="close-btn" @click="handleCancelGroupSelect">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="group-list">
            <div 
              v-for="group in userGroups" 
              :key="group.id"
              :class="['group-item', { active: selectedGroupId === group.id }]"
              @click="selectGroup(group)"
            >
              <div class="group-info">
                <span class="group-name">{{ group.name }}</span>
                <span class="group-role">{{ group.role || '成员' }}</span>
              </div>
              <i class="fas fa-check" v-if="selectedGroupId === group.id"></i>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button 
            class="cancel-btn" 
            @click="handleCancelGroupSelect"
          >
            取消
          </button>
          <button 
            class="confirm-btn" 
            :disabled="!selectedGroupId"
            @click="handleConfirmGroupSelect"
          >
            确认
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SideNav from '@/components/SideNav.vue'
import RichTextEditor from '@/components/RichTextEditor.vue'
import MessagePopup from '@/components/MessagePopup.vue'
import { baseURL } from '@/utils/api'
import axios from 'axios'

export default {
  name: 'ProblemUploadView',
  components: {
    SideNav,
    RichTextEditor,
    MessagePopup
  },
  data() {
    return {
      isSubmitting: false,
      showConfirmDialog: false,
      showMessage: false,
      messageType: 'success',
      messageTitle: '',
      messageText: '',
      uploadedImages: [],
      isSubmitSuccess: false,
      executionLimits: {
        timeUnit: 's',
        memoryUnit: 'MB',
      },
      timeLimit: 2.0,
      memoryLimit: 128, // 默认128MB
      memoryInputValid: true,
      memoryInputStatus: {
        isValid: true,
        message: ''
      },
      showGroupSelector: false,
      selectedGroupId: null,
      userGroups: [],
      problemData: {
        title: '',
        difficulty: '',
        description: '',
        hasLimits: false,
        timeLimit: null,
        memoryLimit: null,
        type: 'public', // 默认为公共题库
        groupId: null,  // 如果是小组题库，这里存储小组ID
      },
      exampleTestCases: [
        { input: '', expectedOutput: '', isExample: true }
      ],
      evaluationTestCases: [
        { input: '', expectedOutput: '', isExample: false }
      ],
      isDestroying: false,
      submittedImageIds: []
    }
  },
  methods: {
    async handleImageUpload(file) {
      if (this.isDestroying) return
      
      try {
        const formData = new FormData()
        formData.append('image', file)
        
        const response = await fetch(`${baseURL}/upload-image`, {
          method: 'POST',
          body: formData
        })
        
        const result = await response.json()
        if (result.success) {
          this.problemData.description += `<img src="${result.url}" alt="上传图片" />`
          this.uploadedImages.push({
            url: result.url,
            id: result.id
          })
        } else {
          this.showMessageWithType('error', '上传失败', '图片上传失败，请重试！')
        }
      } catch (error) {
        console.error('图片上传错误:', error)
        this.showMessageWithType('error', '错误', '上传图片时发生错误，请重试！')
      }
    },
    async handleImageDelete(imageUrl) {
      if (this.isDestroying) return
      
      try {
        const image = this.uploadedImages.find(img => img.url === imageUrl)
        if (image) {
          console.log('正在删除编辑器中的图片:', image.url)
          
          const response = await fetch(`${baseURL}/delete-image/${image.id}`, {
            method: 'DELETE'
          })
          
          const result = await response.json()
          if (result.success) {
            console.log('图片删除成功:', image.url)
            this.uploadedImages = this.uploadedImages.filter(img => img.id !== image.id)
            this.problemData.description = this.problemData.description.replace(
              `<img src="${image.url}" alt="上传图片" />`,
              ''
            )
          } else {
            console.log('图片删除失败:', image.url, result)
          }
        }
      } catch (error) {
        console.error('图片删除错误:', error)
        this.showMessageWithType('error', '错误', '删除图片时发生错误，请重试！')
      }
    },
    handleTimeUnitChange() {
      const oldValue = this.timeLimit
      const oldUnit = this.executionLimits.timeUnit === 's' ? 'ms' : 's'
      const newUnit = this.executionLimits.timeUnit
      
      if (oldUnit === 'ms' && newUnit === 's') {
        this.timeLimit = oldValue / 1000
      } else if (oldUnit === 's' && newUnit === 'ms') {
        this.timeLimit = oldValue * 1000
      }
    },
    handleMemoryUnitChange() {
      const oldValue = this.memoryLimit
      const oldUnit = this.executionLimits.memoryUnit === 'MB' ? 'KB' : 'MB'
      const newUnit = this.executionLimits.memoryUnit
      
      if (oldUnit === 'KB' && newUnit === 'MB') {
        this.memoryLimit = oldValue / 1024
      } else if (oldUnit === 'MB' && newUnit === 'KB') {
        this.memoryLimit = oldValue * 1024
      }
      this.validateMemoryLimit()
    },
    validateMemoryLimit() {
      const minMemory = this.executionLimits.memoryUnit === 'MB' ? 2 : 2048 // 2MB
      const maxMemory = this.executionLimits.memoryUnit === 'MB' ? 512 : 524288 // 512MB
      const currentValue = this.memoryLimit

      if (currentValue < minMemory) {
        this.memoryInputStatus = {
          isValid: false,
          message: `内存不能小于 ${this.executionLimits.memoryUnit === 'MB' ? '2MB' : '2048KB'}`
        }
        this.memoryInputValid = false
      } else if (currentValue > maxMemory) {
        this.memoryInputStatus = {
          isValid: false,
          message: `内存不能大于 ${this.executionLimits.memoryUnit === 'MB' ? '512MB' : '524288KB'}`
        }
        this.memoryInputValid = false
      } else {
        this.memoryInputStatus = {
          isValid: true,
          message: ''
        }
        this.memoryInputValid = true
      }
    },
    addTestCase(type) {
      const newCase = { input: '', expectedOutput: '', isExample: type === 'example' }
      if (type === 'example') {
        this.exampleTestCases.push(newCase)
      } else {
        this.evaluationTestCases.push(newCase)
      }
    },
    removeTestCase(type, index) {
      if (type === 'example') {
        this.exampleTestCases.splice(index, 1)
      } else {
        this.evaluationTestCases.splice(index, 1)
      }
    },
    showMessageWithType(type, title, text) {
      this.messageType = type
      this.messageTitle = title
      this.messageText = text
      this.showMessage = true
    },
    setProblemType(type) {
      this.problemData.type = type
      if (type === 'group') {
        this.showGroupSelector = true
      } else {
        this.problemData.groupId = null
      }
    },
    selectGroup(group) {
      this.selectedGroupId = group.id;
    },
    handleConfirmGroupSelect() {
      this.problemData.groupId = this.selectedGroupId;
      this.showGroupSelector = false;
    },
    handleCancelGroupSelect() {
      // 如果是从小组详情页过来的，取消时不改变类型
      if (!this.$route.query.group_id) {
        if (!this.problemData.groupId) {
          this.problemData.type = 'public';
        }
      }
      this.selectedGroupId = this.problemData.groupId;
      this.showGroupSelector = false;
    },
    submitProblem() {
      // 基本验证
      if (!this.problemData.title.trim()) {
        this.showMessageWithType('warning', '验证失败', '请输入题目标题')
        return
      }
      if (!this.problemData.difficulty) {
        this.showMessageWithType('warning', '验证失败', '请选择题目难度')
        return
      }
      if (!this.problemData.description.trim()) {
        this.showMessageWithType('warning', '验证失败', '请输入题目描述')
        return
      }
      if (this.problemData.type === 'group' && !this.problemData.groupId) {
        this.showMessageWithType('warning', '验证失败', '请选择要上传到的小组')
        return
      }

      // 验证测试用例
      const hasValidExampleCase = this.exampleTestCases.some(
        tc => tc.expectedOutput.trim() // 只验证预期输出必填
      )
      const hasValidEvalCase = this.evaluationTestCases.some(
        tc => tc.expectedOutput.trim() // 只验证预期输出必填
      )

      if (!hasValidExampleCase) {
        this.showMessageWithType('warning', '验证失败', '请至少添加一个有效的示例测试用例（需要填写预期输出）')
        return
      }
      if (!hasValidEvalCase) {
        this.showMessageWithType('warning', '验证失败', '请至少添加一个有效的评测测试用例（需要填写预期输出）')
        return
      }

      // 显示确认对话框
      this.showConfirmDialog = true
    },
    async handleConfirmSubmit() {
      this.isSubmitting = true;
      this.showConfirmDialog = false;

      try {
        // 从localStorage获取userId
        const userId = localStorage.getItem('userId');
        if (!userId) {
          throw new Error('用户未登录，请先登录');
        }

        // 保存当前上传的图片IDs，用于最后的处理
        const currentImageIds = this.uploadedImages.map(img => img.id);

        // 准备提交数据，按照后端结构体名称修改为下划线格式
        const submitData = {
          title: this.problemData.title,
          description: this.problemData.description,
          difficulty: this.problemData.difficulty,
          has_limits: this.problemData.hasLimits ? true : false,
          time_limit: this.problemData.hasLimits ? 
            (this.executionLimits.timeUnit === 'ms' ? this.timeLimit / 1000 : this.timeLimit) : 
            null,
          memory_limit: this.problemData.hasLimits ? 
            (this.executionLimits.memoryUnit === 'MB' ? this.memoryLimit * 1024 : this.memoryLimit) : 
            null,
          type: this.problemData.type.toUpperCase(),
          group_id: this.problemData.groupId,
          creator_id: parseInt(userId),
          review_status: 'REVIEWING',
          status: 1
        };

        const response = await fetch(`${baseURL}/CodeQuestion-service/problems/create`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(submitData)
        });

        if (!response.ok) {
          throw new Error('网络请求失败');
        }

        const result = await response.json();
        
        if (result.result === 'success') {
          console.log('题目创建成功:', result);
          
          // 获取创建的题目ID
          const problemId = result.problem.id;
          
          // 准备测试用例数据
          await this.submitTestCases(problemId);
          
          // 提交成功后的处理
          this.isSubmitSuccess = true;
          
          // 保存已提交的图片ID
          this.submittedImageIds = [...currentImageIds];
          
          // 立即清空图片数组
          this.uploadedImages = [];
          
          // 同时使用sessionStorage来确保在组件销毁时也能识别已提交的图片
          sessionStorage.setItem('submittedProblemImages', JSON.stringify(currentImageIds));
          
          this.showMessageWithType('success', '提交成功', result.message || '题目已提交，等待审核');
          
          // 提交成功后返回
          setTimeout(() => {
            // 如果是从小组详情页来的，提交成功后返回小组详情页
            if (this.$route.query.group_id) {
              this.$router.push(`/group/${this.$route.query.group_id}`);
            } else {
              // 否则返回题目列表
              this.$router.push('/problems');
            }
          }, 2000);
        } else {
          throw new Error(result.message || '创建失败');
        }

      } catch (error) {
        console.error('提交题目失败:', error);
        this.showMessageWithType('error', '提交失败', error.message || '提交题目时发生错误，请重试');
      } finally {
        this.isSubmitting = false;
      }
    },

    // 改进submitTestCases方法，在提交前处理测试用例格式
    async submitTestCases(problemId) {
      try {
        // 1. 准备示例测试用例 - 先格式化，再转换为JSON字符串
        // 1.1 处理格式，确保每个示例测试用例是正确的格式
        const formattedExampleTestCases = this.exampleTestCases.map(tc => {
          // 创建一个新对象，避免修改原始对象
          const formattedTestCase = {...tc};
          
          // 确保输入格式正确 - 不需要用户自己添加测试用例数量
          // 我们假设每个示例都是单独的一个测试用例
          if (formattedTestCase.input && !formattedTestCase.input.trim().match(/^\d+\s*\n/)) {
            // 如果输入不是以数字开头后跟换行，添加"1\n"前缀
            formattedTestCase.input = "1\n" + formattedTestCase.input;
          }
          
          return formattedTestCase;
        });
        
        // 1.2 转换为JSON字符串
        const exampleJson = JSON.stringify(formattedExampleTestCases);
        
        // 2. 准备评测用例 - 按Judge0格式处理
        const judgeTests = this.evaluationTestCases.filter(tc => tc.expectedOutput.trim());
        
        // 2.1 构建stdin - 第一行是测试用例数量，然后是每个测试用例的输入
        let judgeStdin = `${judgeTests.length}\n`;
        judgeStdin += judgeTests.map(tc => tc.input).join('\n');
        
        // 2.2 构建expected_output - 每行一个期望输出
        const judgeExpectedOutput = judgeTests.map(tc => tc.expectedOutput).join('\n');
        
        // 3. 准备提交数据
        const testCaseData = {
          problem_id: problemId,
          example_json: exampleJson,
          judge_stdin: judgeStdin,
          judge_expected_output: judgeExpectedOutput
        };
        
        console.log('提交测试用例数据:', testCaseData);
        
        // 4. 调用后端API
        const response = await fetch(`${baseURL}/CodeQuestion-service/problems/insertTestCase`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(testCaseData)
        });
        
        if (!response.ok) {
          throw new Error('测试用例提交失败');
        }
        
        const result = await response.json();
        
        if (result.result !== 'success') {
          console.warn('测试用例提交警告:', result.message);
        } else {
          console.log('测试用例提交成功:', result);
        }
        
        return result;
      } catch (error) {
        console.error('提交测试用例失败:', error);
        // 不抛出错误，避免影响主流程
        return { result: 'fail', message: error.message };
      }
    },
    async fetchUserGroups() {
      try {
        // 获取用户所在的小组列表
        const userId = localStorage.getItem('userId');
        if (!userId) {
          console.error('用户未登录，无法获取小组列表');
          return;
        }

        // 如果已经有小组ID了，就不需要再加载全部小组
        if (this.problemData.groupId) {
          return;
        }

        // 获取我创建的小组
        const createdResponse = await axios.get(`${baseURL}/CodeQuestion-service/groups/my-created/${userId}`);
        
        // 获取我加入的小组
        const joinedResponse = await axios.get(`${baseURL}/CodeQuestion-service/groups/my-joined/${userId}`);
        
        if (createdResponse.data.result === 'success' && joinedResponse.data.result === 'success') {
          // 合并小组列表并标记角色
          const createdGroups = createdResponse.data.groups.map(group => ({
            id: group.id,
            name: group.name,
            role: '管理员'
          }));
          
          const joinedGroups = joinedResponse.data.groups.map(group => ({
            id: group.id,
            name: group.name,
            role: '成员'
          }));
          
          // 创建一个Map用于去重，优先保留管理员角色
          const groupMap = new Map();
          
          // 先添加管理员角色的小组
          createdGroups.forEach(group => {
            groupMap.set(group.id, group);
          });
          
          // 再添加成员角色的小组，但不覆盖已有的管理员角色
          joinedGroups.forEach(group => {
            if (!groupMap.has(group.id)) {
              groupMap.set(group.id, group);
            }
          });
          
          // 转换回数组
          this.userGroups = Array.from(groupMap.values());
          console.log('获取到的用户小组列表:', this.userGroups);
        } else {
          console.error('获取小组列表失败:', createdResponse.data.message, joinedResponse.data.message);
        }
      } catch (error) {
        console.error('获取用户小组列表失败:', error);
      }
    }
  },
  async created() {
    // 从URL查询参数中获取小组ID和名称
    const groupId = this.$route.query.group_id;
    const groupName = this.$route.query.group_name;
    
    if (groupId) {
      // 如果有小组ID参数，则设置题目类型为小组题库
      this.problemData.type = 'group';
      this.problemData.groupId = parseInt(groupId);
      // 记录小组信息，方便显示
      this.userGroups = [{
        id: parseInt(groupId),
        name: groupName || '小组'
      }];
      this.selectedGroupId = parseInt(groupId);
    }
    
    // 获取用户所在的小组列表
    this.fetchUserGroups();
  },
  beforeDestroy() {
    this.isDestroying = true;
    
    // 获取会话存储中的已提交图片IDs
    const storedSubmittedImages = sessionStorage.getItem('submittedProblemImages');
    const submittedIds = storedSubmittedImages ? JSON.parse(storedSubmittedImages) : [];
    
    // 合并本地的submittedImageIds和sessionStorage中的值
    const allSubmittedIds = [...this.submittedImageIds, ...submittedIds];
    
    console.log('组件销毁时的状态:', {
      isSubmitSuccess: this.isSubmitSuccess,
      uploadedImagesCount: this.uploadedImages.length,
      submittedIds: allSubmittedIds
    });
    
    // 如果明确知道提交成功或者没有图片需要删除，直接返回
    if (this.isSubmitSuccess || this.uploadedImages.length === 0) {
      console.log('跳过删除图片:', this.isSubmitSuccess ? '提交成功' : '没有需要删除的图片');
      // 清除会话存储
      if (this.isSubmitSuccess) {
        sessionStorage.removeItem('submittedProblemImages');
      }
      return;
    }
    
    // 过滤出需要删除的图片 - 排除已知提交成功的图片
    const imagesToDelete = this.uploadedImages.filter(image => !allSubmittedIds.includes(image.id));
    
    console.log('需要删除的图片列表:', imagesToDelete.map(img => img.url));
    
    // 只删除未成功提交的图片
    imagesToDelete.forEach(image => {
      console.log('正在删除图片:', image.url);
      fetch(`${baseURL}/delete-image/${image.id}`, { method: 'DELETE' })
        .then(response => response.json())
        .then(result => {
          console.log('图片删除结果:', image.url, result);
        })
        .catch(error => {
          console.error('清理图片失败:', image.url, error);
        });
    });
    
    // 清除会话存储
    if (this.isSubmitSuccess) {
      sessionStorage.removeItem('submittedProblemImages');
    }
  }
}
</script>

<style scoped>
.problem-upload {
  min-height: 100vh;
  background: #f0f7ff;
}

.main-content {
  margin-left: 60px;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

h1 {
  color: #2c3e50;
  margin: 0;
}

.section {
  background: white;
  border-radius: 10px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

h2 {
  color: #2c3e50;
  margin: 0 0 20px 0;
  font-size: 18px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #5b7b9a;
}

.form-input,
.form-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-input:focus,
.form-select:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
  outline: none;
}

.editor-container {
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  overflow: hidden;
}

.problem-editor {
  min-height: 300px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.limits-toggle {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #cbd5e0;
  transition: .4s;
  border-radius: 24px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #3498db;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.limits-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.limit-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.limit-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.limit-input {
  width: 120px;
  padding: 8px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
}

.unit-select {
  width: 80px;
  padding: 8px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
}

.input-error {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}

.test-cases-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.test-case-group h3 {
  color: #2c3e50;
  margin: 0 0 16px 0;
  font-size: 16px;
}

.test-case-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.test-case-item {
  border: 1px solid #e8f4ff;
  border-radius: 8px;
  padding: 16px;
  background: #f8faff;
}

.test-case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.test-case-header h4 {
  margin: 0;
  color: #5b7b9a;
  font-size: 14px;
}

.delete-btn {
  padding: 4px 8px;
  border: none;
  background: none;
  color: #f56c6c;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
}

.delete-btn:hover {
  background: #fef0f0;
}

.test-case-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.case-textarea {
  height: 100px;
  padding: 8px;
  border: 1px solid #e8f4ff;
  border-radius: 4px;
  resize: vertical;
  font-family: monospace;
  font-size: 14px;
}

.add-case-btn {
  padding: 12px;
  border: 2px dashed #e8f4ff;
  border-radius: 8px;
  background: none;
  color: #3498db;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.add-case-btn:hover {
  border-color: #3498db;
  background: #f8faff;
}

.submit-btn {
  padding: 10px 20px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: #3aa876;
}

.submit-btn:disabled {
  background: #a8e2c9;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .limits-content,
  .test-case-content {
    grid-template-columns: 1fr;
  }
}

.library-type-selector {
  display: flex;
  gap: 16px;
}

.type-btn {
  flex: 1;
  padding: 12px;
  border: 1px solid #e8f4ff;
  border-radius: 8px;
  background: white;
  color: #5b7b9a;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.type-btn:hover {
  border-color: #3498db;
  color: #3498db;
}

.type-btn.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

.modal-content {
  position: relative;
  width: 90%;
  max-width: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
  z-index: 1001;
}

.modal-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e8f4ff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  color: #5b7b9a;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f8faff;
  color: #3498db;
}

.modal-body {
  padding: 24px;
  max-height: 400px;
  overflow-y: auto;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8f4ff;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #f8faff;
}

.confirm-btn {
  padding: 8px 24px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.confirm-btn:hover {
  background: #2980b9;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.3);
}

.confirm-btn:active {
  transform: translateY(0);
  box-shadow: none;
}

.confirm-btn:disabled {
  background: #b3d7ff;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.confirm-btn:disabled:hover {
  background: #b3d7ff;
  transform: none;
  box-shadow: none;
}

.cancel-btn {
  padding: 8px 24px;
  background: white;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  color: #5b7b9a;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.cancel-btn:hover {
  border-color: #3498db;
  color: #3498db;
  background: #f8faff;
  transform: translateY(-1px);
}

.cancel-btn:active {
  transform: translateY(0);
}

.group-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.group-item {
  padding: 16px;
  border: 1px solid #e8f4ff;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

.group-item:hover {
  border-color: #3498db;
  background: #f8faff;
}

.group-item.active {
  border-color: #3498db;
  background: #f0f7ff;
}

.group-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.group-name {
  font-size: 16px;
  color: #2c3e50;
}

.group-role {
  font-size: 12px;
  color: #5b7b9a;
}

.fa-check {
  color: #3498db;
  font-size: 16px;
}

/* 添加动画效果 */
.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

.modal-content-enter-active,
.modal-content-leave-active {
  transition: transform 0.3s ease;
}

.modal-content-enter-from,
.modal-content-leave-to {
  transform: translateY(20px);
}

.test-case-tips {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 8px;
  background-color: #e6f7ff;
  border-left: 4px solid #1890ff;
  display: flex;
  align-items: flex-start;
}

.test-case-tips i {
  font-size: 18px;
  color: #1890ff;
  margin-right: 12px;
  margin-top: 2px;
}

.test-case-tips h3 {
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 16px;
}

.test-case-tips ul {
  margin: 0;
  padding-left: 20px;
}

.test-case-tips li {
  margin-bottom: 6px;
}

.test-case-tips code {
  background: #f0f2f5;
  padding: 2px 5px;
  border-radius: 3px;
  font-family: monospace;
}

.alert-evaluation {
  background-color: #fff7e6;
  border-left-color: #fa8c16;
}

.alert-evaluation i {
  color: #fa8c16;
}
</style> 